package org.mozhu.mboot.admin.system.auth.service;

import org.mozhu.mboot.admin.system.auth.entity.GroupAuth;
import org.mozhu.mboot.admin.system.group.service.UserGroupRelationService;
import org.mozhu.mboot.admin.system.privilege.entity.Permission;
import org.mozhu.mboot.admin.system.privilege.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service("userGroupAuthorityService")
public class UserGroupAuthorityService extends AbstractGroupAuthorityService implements AuthorityService {

    @Autowired
    UserGroupRelationService userGroupRelationService;

    @Override
    public Set<String> findStringRoles(Long userId) {
        List<GroupAuth> groupAuths = getGroupAuths(userId);
        Set<Long> roleIds = groupAuthsToRoleIds(groupAuths);
        List<Role> defaultRoles = roleService.findAvailableRoles(roleIds);
        return stringRoles(defaultRoles);
    }

    @Override
    public Set<String> findStringPermissions(Long userId) {
        List<GroupAuth> groupAuths = getGroupAuths(userId);
        Set<Long> permissionIds = groupAuthsToPermissionIds(groupAuths);
        List<Permission> permissions = permissionService.findAvailablePermissions(permissionIds);
        return stringPermissions(permissions);
    }

    protected List<GroupAuth> getGroupAuths(Long userId) {
        Set<Long> groupIds = userGroupRelationService.findGroupIds(userId);
        Set<Long> defaultGroupIds = groupService.findDefaultGroupIds();
        groupIds.addAll(defaultGroupIds);
        return groupAuthService.findAllById(groupIds);
    }
}
